package main

import (
	"entry_task/backend/src/utils"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"time"
	"unsafe"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

type UserInfoTab struct {
	Id                int64     `xorm:"pk comment('id') BIGINT(20)"`
	Username          string    `xorm:"not null comment('用户名') unique VARCHAR(64)"`
	Password          string    `xorm:"not null comment('密码（sha256）') VARCHAR(64)"`
	ProfilePictureUrl string    `xorm:"comment('头像url') VARCHAR(128)"`
	Nickname          string    `xorm:"comment('昵称') VARCHAR(64)"`
	UpdateTime        time.Time `xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"`
	CreateTime        time.Time `xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"`
}

/**
测试用例，批量插入客户用,建议最多150条/次
*/
func BatchInsert(engine *xorm.Engine, users *[]UserInfoTab) int64 {
	affected, err := engine.Insert(&users)
	utils.CheckErr(err)
	return affected
}

func getMaxId(engine *xorm.Engine) int {
	sql := "select max(id) as maxId from user_info_tab"
	results, err := engine.QueryString(sql)
	if err != nil {
		panic(err)
	}
	maxString := results[0]["maxId"]
	max, _ := strconv.ParseInt(maxString, 0, 0)
	fmt.Printf("getMaxId=%v", max)
	return *(*int)(unsafe.Pointer(&max))
}

var threadSize = 2

func main() {
	engine, _ := xorm.NewEngine("mysql", "root:happy15699@tcp(localhost:3306)/entry_task_db?charset=utf8mb4")

	defer engine.Close()

	engine.ShowSQL(false)
	engine.SetLogLevel(log.LOG_ERR)
	engine.SetMaxOpenConns(50)
	engine.SetMaxIdleConns(10)

	maxId := getMaxId(engine)
	for i := maxId + 1; i < 1000_0000; {
		i = singleInsertData(engine, i)
	}
}

const size = 150

func singleInsertData(engine *xorm.Engine, fromId int) int {
	var users = make([]UserInfoTab, size)
	for i := fromId; i < fromId+size; i++ {
		users[i%size].Id = int64(i)
		users[i%size].Username = fmt.Sprintf("us%d", i)
		users[i%size].Nickname = fmt.Sprintf("nk%d", i)
		users[i%size].Password = utils.LoginCrypto(fmt.Sprintf("pw%d", i))
		users[i%size].ProfilePictureUrl = ""
		users[i%size].UpdateTime = time.Now()
		users[i%size].CreateTime = time.Now()
	}
	affected, err := engine.Insert(&users)
	if err != nil {
		fmt.Printf("插入异常")
		return 0
	}
	fmt.Printf("插入成功:%d,当前是第%d条\n", affected, fromId)

	return fromId + size
}

func doInsertData(engine *xorm.Engine, maxId int, threshold int, md int) {
	var users [150]UserInfoTab
	for i := maxId; i < threshold; {
		if i%md == 0 {
			i = i + threadSize
			users[i/threadSize].Id = int64(i)
			users[i].Username = fmt.Sprintf("us%d", i)
			users[i].Nickname = fmt.Sprintf("nk%d", i)
			users[i].Password = utils.LoginCrypto(fmt.Sprintf("pw%d", i))
		} else {
			i++
		}
	}
}
